/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.Calculate;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import com.xcl.calculator.slice.Calculate.KeXue.SetCal;
import com.xcl.calculator.slice.Calculate.KeXue.SetProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.agp.components.TextField;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.List;

/**
 * The type Kx cal ability slice.
 *
 * @author Xcl
 * @date 2022 /1/29
 * @package com.xcl.calculator.slice.Calculate
 */
public class KXCalAbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "Cal0AbilitySlice");
    /**
     * The constant ans.
     */
    public static TextField ans;
    /**
     * The constant que.
     */
    public static TextField que;
    /**
     * The constant context1.
     */
    public static Context context1;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;

    /**
     * Gets data.
     *
     * @return the data
     */
    private static List<SetCal> getData() {
        ArrayList<SetCal> data = new ArrayList<>();
        data.add(new SetCal("√", "^", "!", "(", ")"));
        data.add(new SetCal(",", "∞", "i", "x", "°"));
        data.add(new SetCal("7", "8", "9", "←", "AC"));
        data.add(new SetCal("4", "5", "6", "•", "/"));
        data.add(new SetCal("1", "2", "3", "+", "-"));
        data.add(new SetCal("0", ".", "%", "e", "="));
        data.add(new SetCal("ans", "π", "k", "F", "h"));
        data.add(new SetCal("ћ", "γ", "φ", "c", "N"));
        data.add(new SetCal("R", "K", "Γ", "G", "Φ"));
        data.add(new SetCal("true", "false", "me", "mn", "mp"));
        data.add(new SetCal("rand", "randInt", "abs", "lg", "ln"));
        data.add(new SetCal("re", "im", "min", "max", "log"));
        data.add(new SetCal("sin", "cos", "tan", "arg", "eval"));
        data.add(new SetCal("asin", "acos", "atan", "norm", "conj"));
        data.add(new SetCal("diff", "sum", "lim", "fzero", "integ"));
        data.add(new SetCal("exp", "gcd", "lcm", "perm", "comb"));
        data.add(new SetCal("round", "floor", "ceil", "sign", "remn"));
        data.add(new SetCal("prime", "isPrime", "cbrt", "root", "Help"));
        return data;
    }

    /**
     * 切换后台并销毁，防止手表抽风
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.terminateAbility();
    }

    /**
     * 开始
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_kxcalm);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_kxcalt);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }

            ListContainer listContainer = (ListContainer) this.findComponentById(ResourceTable.Id_listContainercal);
            listContainer.setContentOffSet(32, 16);
            SetProvider provider = new SetProvider(KXCalAbilitySlice.getData(), this);

            listContainer.enableScrollBar(Component.AXIS_Y, true);
            listContainer.setScrollbarRoundRect(true);
            listContainer.setScrollbarRadius(listContainer.getScrollbarThickness() / 2);
            ans = (TextField) this.findComponentById(ResourceTable.Id_kx_ans_field);
            que = (TextField) this.findComponentById(ResourceTable.Id_kx_que_field);
            ans.setEnabled(false);
            Context context = this.getContext();
            context1 = context;
            listContainer.setItemProvider(provider);
            this.findComponentById(ResourceTable.Id_kxcal).setTouchEventListener(this);
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 数据展示
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(120)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    this.ShowDialog("到头了...");
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Calculate.CalMenuAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156) {
                    //this.ShowDialog("到头了...");
                    //XLog.info(label, "上滑了");
                } else if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156) {
                    //this.ShowDialog("到头了...");
                    //XLog.info(label, "下滑了");
                } else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }

    /**
     * 退出
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return boolean boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }
}
